package concurrency;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther DRevelation
 * @Date 2020-06-09 下午 14:18
 * @Desc
 */
public class WaitNotifyDemo {
    private static final int MAX_SIZE = 5;

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(MAX_SIZE);
        for (int i = 0; i < 5; i++) {
            exec.submit(new Provider(queue));
        }
        for (int i = 0; i < 5; i++) {
            exec.submit(new Consumer(queue));
        }
    }

    static class Provider implements Runnable {

        private BlockingQueue<Integer> queue;

        public Provider(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            synchronized (queue) {
                while (queue.size() == MAX_SIZE) {
                    try {
                        System.out.println("队列已满，生产者【" + Thread.currentThread().getName() + "】开始等待");
                        queue.wait();
                        System.out.println("生产者【" + Thread.currentThread().getName() + "】退出等待");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            Random random = new Random();
            queue.add(random.nextInt(10));
            System.out.println("生产者生产");
            queue.notifyAll();
        }
    }

    static class Consumer implements Runnable {

        private BlockingQueue<Integer> queue;
        private static final int MAX_SIZE = 10;

        public Consumer(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            synchronized (queue) {
                while (queue.size() == 0) {
                    try {
                        System.out.println("队列已空，消费者【" + Thread.currentThread().getName() + "】");
                        queue.wait();
                        System.out.println("消费者【" + Thread.currentThread().getName() + "】退出等待");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            try {
                Integer r = queue.take();
                System.out.println("消费者消费");
                queue.notifyAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

